#!/user/bin/python
# -*- coding:utf-8 -*-
#filename:mysqldb.py


'''
mysql数据库链接操作管理

 
Created on 2011-8-23

@author: zc
'''

import web
import os
from controllers.utils import logger
logger = logger.logger()

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

class mysqldb():
    '''    mysql数据库操作封装，使用web.py自带mysql数据操作方法    '''

    def __init__( self ):
        '''        初始化参数        '''
        self.__dbn = "mysql"
        self.__user = "tfeet"
        self.__pwd = "vOR1kFumY" 
        self.__db = "tinyfeet"
        self.__host = "0.0.0.0"
        self.__port = 3306
        self.__dbo = web.database( dbn = self.__dbn, user = self.__user, pw = self.__pwd, db = self.__db, host = self.__host, port = self.__port , charset = 'utf8' )
      
    
    def query( self, sqlstr ):
        """ 执行查询语句，返回查询结果，查询失败返回None """
        res = None
        try:
            res = self.__dbo.query( sqlstr )
        except Exception, data:
            res = None
            logger.error( u"查询失败：%s,%s" % ( sqlstr, data ) )
            print u"查询失败：", sqlstr, data
        finally:
            return res
        
        
    def insert( self, tbn, seqname = None, _test = False, **colval ):
        """ 增加记录 """
        res = -1
        t = self.__dbo.transaction()
        try:
            res = self.__dbo.insert( tbn , seqname = None, _test = False, **colval )
        except Exception, data:
            res = -1
            t.rollback()
            logger.error( u"增加记录失败：%s,%s" % ( tbn, data ) )
            print u"增加记录失败：", tbn, data
        else:
            t.commit()
            raise
        finally:
            return res
    

    def execsql( self, sqlstr ):
        """  执行更新删除等带事物的查询脚本 """
        res = -1
        t = self.__dbo.transaction()
        try:
            res = self.__dbo.query( sqlstr )
        except Exception, data:
            res = -1
            t.rollback()
            logger.error( u"SQL执行失败：%s,%s" % ( sqlstr, data ) )
            print u"SQL执行失败：", sqlstr, data
        else:
            t.commit()
            raise
        finally:
            return res


if __name__ == "__main__":
    dbo = mysqldb()
    print 'will....'
    #row = dbo.insert( 'tfeet', seqname = 'tfid', _test = True, uid = '2222', location = '1111' )
    row = dbo.execsql( "update tfeet set location = '00' where tfid = 278" )
    print row
    
    
